﻿using System;
using System.Collections;
using System.Reflection;

namespace QuickTest.Core.TestRunner
{
    /// <summary>
    /// The AssemblyResolver class is used to load assemblies into a remote AppDomain.
    /// </summary>
    public class AssemblyResolver : MarshalByRefObject, IDisposable
    {
        private class AssemblyCache
        {
            private readonly Hashtable resolvedAssemblies = new Hashtable();

            public bool Contains(string name)
            {
                return resolvedAssemblies.ContainsKey(name);
            }

            public Assembly Resolve(string name)
            {
                if (resolvedAssemblies.ContainsKey(name))
                    return (Assembly) resolvedAssemblies[name];

                return null;
            }

            public void Add(string name, Assembly assembly)
            {
                resolvedAssemblies[name] = assembly;
            }
        }

        private readonly AssemblyCache assemblyCache = new AssemblyCache();

        public AssemblyResolver()
        {
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
        }

        public void Dispose()
        {
            AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
        }

        public void AddFile(string file)
        {
            Assembly assembly = Assembly.LoadFrom(file);
            assemblyCache.Add(assembly.GetName().FullName, assembly);
        }

        private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            string fullName = args.Name;

            // Only resolve using full name
            if (fullName.IndexOf(',') == -1) return null;

            if (assemblyCache.Contains(fullName))
            {
                return assemblyCache.Resolve(fullName);
            }

            return null;
        }
    }
}